package edu.mse.camel.client.posterboard.ui.actions;

import java.util.Calendar;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import edu.mse.camel.client.eventbus.pubsub.EventManager;
import edu.mse.camel.client.events.peer.CallForAttentionEvent;
import edu.mse.camel.client.events.peer.ReceiveChatEvent;
import edu.mse.camel.client.events.peer.SendChatEvent;
import edu.mse.camel.client.events.peer.SendGenericPeerEvent;
import edu.mse.camel.client.posterboard.ui.PosterboardPlugin;
import edu.mse.camel.client.session.team.TEAMMEMBER_STATUS;
import edu.mse.camel.client.session.team.TeamList;

public class CallForAttentionActionDelegate implements IViewActionDelegate {

	private static final String CALL_MSG = "*****Look at my Viewport!!*****";

	@Override
	public void init(IViewPart view) {
		// TODO Auto-generated method stub

	}

	@Override
	public void run(IAction action) {
		if (TeamList.getInstance().getMyStatus().equals(TEAMMEMBER_STATUS.SESSION)) {
			String me = TeamList.getInstance().getMe().getName();
			CallForAttentionEvent call = 
				new CallForAttentionEvent(me);
			SendGenericPeerEvent genericEvent = new SendGenericPeerEvent();
			genericEvent.writeObject(call);
			// No need to cache this event for now
			EventManager.getInstance().dispatchEventAsynchronous(genericEvent, false);
			SendChatEvent sce = 
				new SendChatEvent(CALL_MSG);
			EventManager.getInstance().dispatchEventAsynchronous(sce, true);
			
			Calendar now = Calendar.getInstance();
			ReceiveChatEvent chatEvent = new ReceiveChatEvent(
					CALL_MSG, me, now.getTime());
			EventManager.getInstance().dispatchEventAsynchronous(chatEvent, true);
			
			
		} else {
			ErrorDialog ed = new ErrorDialog(
					new Shell(),
					"Posterboard Error",
					"You cannot call for attention",
					new Status(IStatus.ERROR, PosterboardPlugin.PLUGIN_ID, "You are not in a session"),
					IStatus.ERROR);
			ed.open();
		}

	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		// TODO Auto-generated method stub

	}

}
